<!--
 * @author  dumeng
 多选题
-->
<template>
  <div class="question-duoxuan">
    <el-form
      ref="duoxuanform"
      :model="baseform"
      :rules="baserules"
      class="dataForm nomt"
      label-position="right"
      label-width="100px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="题干" prop="stem">
            <custom-textarea
                v-model="baseform.stem"
                :disabled="disabled"
                flag="duoxuancontent"
                placeholder="题干这里填写题目描述"
                type="content"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-checkbox-group v-model="rightAnswer">
            <el-form-item
              v-for="(answer, index) in baseform.opts"
              :key="index"
              :label="`备选答案${index+1}`"
              class="options"
              required
            >
              <custom-textarea
                  @focus="markIndex(index)"
                  @input="syncValue"
                  v-model="baseform.opts[index]"
                  :disabled="disabled"
                  style="width: 100%;margin-right: 5px;"
                  :flag="`danxuanopt${index}`"
                  placeholder="请输入备选答案"
                  type="option"
              />
              <template v-if="canSelectRa">
                <span v-if="rightA.indexOf(baseform.opts[index]) > -1" class="option-rightasnwer">
                  <i class="el-icon-check" />原正确答案
                </span>
                <span v-else class="option-rightasnwer" />
              </template>
              <el-checkbox :disabled="$parent.$route.name !== 'SkillQuestionManage' && !canSelectRa" :label="baseform.opts[index]">正确答案</el-checkbox>
              <span v-if="!disabled" class="remove-option" @click.prevent="removeOption(index)">
                <i class="el-icon-delete" />
              </span>
            </el-form-item>
          </el-checkbox-group>
        </el-col>
        <el-col v-if="!disabled" :span="24">
          <el-button icon="el-icon-circle-plus" class="add-optiopn" @click="addOption">添加备选答案</el-button>
        </el-col>
        <!--<el-col v-if="!disabled" :span="24">
          <el-checkbox class="order-fixed" v-model="orderFixed">备选答案顺序固定</el-checkbox>
        </el-col>
        <el-col :span="24" class="tip">
          <div>说明文字：对于类似下面的选择题备选答案，不应混淆。请设置“备选答案顺序固定”</div>
          <div>
            举例：A、飞沫传播 B、粪便传播 C、接触传播 D、血液传播
            <span>E、以上都是</span>
          </div>
        </el-col>-->
        <el-col :span="24">
          <el-form-item label="试题解析">
            <el-input
              v-model.trim="baseform.questionAnalysis"
              :rows="2"
              :disabled="disabled"
              type="textarea"
              placeholder="添加试题解析，便于更好的理解答案"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import customTextarea from './CustomTextarea'
export default {
  name: 'Duoxuan',
  components:{customTextarea},
  props: {
    type: {
      type: String,
      default: '20'
    },
    getData: {
      type: Object,
      default: () => { }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    toggleRightAnswer: { // 是否可以切换正确答案
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      baseform: {
        stem: '',
        opts: ['', '', '', ''],
        questionAnalysis: ''
      },
      rightAnswer: [],
      optInAnswerIndex: '', // 当前编辑的选项内容在正确答案中的索引值
      baserules: {
        stem: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        opts: [
          { required: true, message: '请输入备选答案', trigger: 'blur' }
        ]
      },
      orderFixed: true,
      canSelectRa: false,
      rightA: []
    }
  },
  watch: {
    toggleRightAnswer(val) {
      this.canSelectRa = val
    }
  },
  created() {
    this.canSelectRa = false
    if (this.getData && this.getData.id) {
      try {
        if (this.getData.question && this.getData.dealType) {
          this.$set(this.baseform, 'stem', this.getData.question.stem)
          this.$set(this.baseform, 'questionAnalysis', this.getData.question.questionAnalysis)
          this.$set(this.baseform, 'opts', this.getData.opts)
          const answer = this.getData.dealType == 10 ? JSON.parse(this.getData.question.answer) : JSON.parse(this.getData.answer)
          this.$set(this, 'orderFixed', answer.flags && answer.flags.length > 0)
          this.$set(this, 'rightAnswer', answer.answers)
          this.$set(this, 'rightA', JSON.parse(this.getData.question.answer).answers)
          this.canSelectRa = this.getData.dealType != 10
        } else {
          const answer = JSON.parse(this.getData.answer)
          this.$set(this.baseform, 'stem', this.getData.stem)
          this.$set(this.baseform, 'questionAnalysis', this.getData.questionAnalysis)
          this.$set(this.baseform, 'opts', answer.opts)
          this.$set(this, 'orderFixed', answer.flags && answer.flags.length > 0)
          this.$set(this, 'rightAnswer', answer.answers)
          this.$set(this, 'rightA', answer.answers)
        }
      } catch (error) {
        console.log(error)
        this.$message({
          type: 'error',
          message: '参数异常，请重试!',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    }
  },
  methods: {
    /**
     * 删除指定选项
     * @param i
     */
    removeOption(i) {
      if (this.rightAnswer.indexOf(this.baseform.opts[i]) > -1) {
        this.rightAnswer.splice(this.rightAnswer.indexOf(this.baseform.opts[i]), 1)
      }
      this.baseform.opts.splice(i, 1)
    },
    /**
     * 添加选项
     */
    addOption() {
      this.baseform.opts.push('')
    },
    markIndex(i) {
      if (this.baseform.opts[i] && this.rightAnswer.indexOf(this.baseform.opts[i]) > -1) {
        this.optInAnswerIndex = this.rightAnswer.indexOf(this.baseform.opts[i])
      } else {
        this.optInAnswerIndex = -1
      }
    },
    syncValue(val) {
      if (this.optInAnswerIndex > -1) {
        if (val) {
          this.$set(this.rightAnswer, this.optInAnswerIndex, val)
        } else {
          this.rightAnswer.splice(this.optInAnswerIndex, 1)
        }
      }
    },
    getPostData() {
      let params = ''
      if (!this.baseform.opts.some(item => item)) {
        this.$message({
          message: '请填写备选答案！',
          type: 'warning'
        })
        return false
      }
      if (this.baseform.opts.length < 2) {
        this.$message({
          message: '请至少增加两个备选答案！',
          type: 'warning'
        })
        return false
      }
      if (this.rightAnswer.length === 0) {
        this.$message({
          message: '请选择正确答案！',
          type: 'warning'
        })
        return false
      }
      for (var i = 0; i < this.rightAnswer.length; i++) {
        if (this.baseform.opts.indexOf(this.rightAnswer[i]) === -1) {
          this.$message({
            message: '正确答案错误，请重新勾选！',
            type: 'warning'
          })
          return false
        }
      }
      this.$refs.duoxuanform.validate(valid => {
        if (valid) {
          const answer = {
            type: this.type,
            opts: this.baseform.opts.filter(s => { return s && s.trim() }),
            flags: this.orderFixed ? ['备选答案顺序固定'] : [],
            answers: this.rightAnswer.filter(s => { return s && s.trim() })
          }
          params = {
            answer: JSON.stringify(answer),
            stem: this.baseform.stem,
            questionNumber: 1,
            questionAnalysis: this.baseform.questionAnalysis
          }
        }
      })
      return params
    }
  }
}
</script>

<style lang="scss">
.question-duoxuan {
  .el-radio-group {
    width: 100%;
  }
  .options .el-form-item__content {
    display: flex;
    align-items: center;
    .el-input,
    .el-checkbox {
      margin-right: 10px;
    }
  }
  .option-rightasnwer {
    display: inline-block;
    flex-shrink: 0;
    font-size: 14px;
    color: green;
    width: 90px;
    margin-right: 20px;
  }
  .order-fixed {
    margin: 10px 0;
    padding-left: 100px;
  }
  .remove-option {
    cursor: pointer;
  }
  .add-optiopn {
    margin-left: 100px;
    margin-bottom: 10px;
  }
  .tip {
    padding-left: 100px;
    padding-bottom: 10px;
    color: red;
  }
}
</style>
